<script lang="ts" setup>
import type { AxiosRequestConfig } from '@vben/request';

import type { FormSchemaExt } from '#/api/common/model/validateModel';

import { useVbenModal } from '@vben/common-ui';

import { useVbenForm } from '#/adapter/form';
import { getValidateRuleByVben } from '#/api/common/validate';
import {
  SopDocAppApi,
  SopDocAppConfig,
} from '#/api/devOperation/sop/sopDocApp';
import { useMessage } from '#/hooks/web/useMessage';

import { formSchamas } from '../schemas/form';

const emit = defineEmits<Emits>();

interface Emits {
  (e: 'success', docId: string): void;
}

const { createMessage } = useMessage();

const [EditForm, formApi] = useVbenForm({
  showDefaultActions: false,
  ...formSchamas,
});

async function updateRules(
  Api: AxiosRequestConfig,
  customRules?: FormSchemaExt[],
) {
  const list = await getValidateRuleByVben({ Api, customRules });
  formApi.updateSchema(list);
}

const [Modal, modalApi] = useVbenModal({
  async onOpened() {
    // 更新校验规则
    await updateRules(SopDocAppConfig.Save, []);
  },
  onConfirm() {
    formApi.validate().then(async (e: any) => {
      if (e.valid) {
        const values = await formApi.getValues();
        modalApi.setState({ loading: true, confirmLoading: true });
        try {
          const entity = await SopDocAppApi.save(values);

          createMessage.success('保存成功');
          emit('success', entity.id as string);
          modalApi.close();
        } finally {
          modalApi.setState({ loading: false, confirmLoading: false });
        }
      }
    });
  },
});
defineExpose(modalApi);
</script>
<template>
  <Modal title="添加应用" class="w-[60%]">
    <div class="common-form">
      <EditForm />
    </div>
  </Modal>
</template>
<style scoped lang="less">
@import '#/assets/styles/common-form.less';
</style>
